<template>
  <!-- @scroll="handleScroll"  -->
  <el-scrollbar ref="scrollbarRef">
    <div
      class="box-card main"
      style="margin-top: 10px"
      @click="
        () => {
          showScreenPopover = false;
          showbatchPopover = false;
        }
      "
      v-infinite-scroll="load"
      infinite-scroll-delay="500"
      :infinite-scroll-disabled="infiniteScrollDisabled"
    >
      <!--院校/专业/职业-->
      <div class="alitem between" style="padding: 15px 13px 0">
        <div class="alitem">
          <div
            style="margin: 0 10px"
            v-for="(item, idx) in tabslist"
            :key="idx"
            :class="item.id == index ? 'active' : 'tabs'"
            @click="changeTab(idx)"
          >
            {{ item.name }}
          </div>
        </div>
        <div class="userInfo" style="margin-left: 10px; font-size: 14px">
          <span>
            成绩：{{ convertfun() }}

            <el-icon
              class="curr"
              color="#004cf7"
              size="12"
              @click="onClickUpdateScore"
              v-if="!courseNew"
            >
              <EditPen />
            </el-icon>
          </span>
          <span style="margin: 0 35px">
            <el-popover
              placement="bottom"
              :width="248"
              :visible="showbatchPopover"
            >
              <template #reference>
                <el-button
                  @click.stop="
                    !courseNew ? (showbatchPopover = !showbatchPopover) : ''
                  "
                  >{{ batchData.batch }}
                  <el-icon size="13">
                    <ArrowDownBold />
                  </el-icon>
                </el-button>
              </template>
              <el-table
                :show-header="false"
                :header-cell-style="{
                  backgroundColor: '#f5f5f5',
                  color: '#333',
                  'font-weight': '500',
                  'text-align': 'center',
                }"
                :cell-style="{ 'text-align': 'center' }"
                border
                :data="batchDatas"
              >
                <el-table-column prop="batch" width="74" />
                <el-table-column prop="score" width="74" />
                <el-table-column width="74">
                  <template #default="spoce">
                    <el-button
                      style="color: #004cf7"
                      link
                      @click="onClickFillVolunteer(spoce.$index)"
                      >填报</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-popover>
          </span>
          <span class="curr" @click="onClickMyVolunteerList">
            <span>我的志愿表</span>
            (<span style="color: #004cf7">{{ volunteerTotal || 0 }}</span
            >)
          </span>
        </div>
      </div>
      <div>
        <div v-show="index == 0" @click.stop="handleTabCkick">
          <schoolDate
            ref="schoolDateinfo"
            :schoolData="schoolData"
          ></schoolDate>
        </div>
        <div v-show="index == 1">
          <specialty
            ref="majorDataInfo"
            :batchInfo="batchData"
            :specialtyData="specialtyData"
            :zyType="Number(zy_type)"
            @emitMajorEnrollType="emitMajorEnrollType"
            @addMojoyType="addMojoyType"
          ></specialty>
        </div>
        <div v-show="index == 2">
          <career ref="jobDataInfo" :careerData="careerData"></career>
        </div>
        <!--筛选条件-->
        <div class="screen matop between" @click.stop="handleTabCkick">
          <div class="screenSize" style="width: 65px">筛选条件:</div>
          <div class="flexwrap" style="width: 100%">
            <div
              class="screenTab between flexwrap"
              v-for="(item, idx) in userSearchDate"
              :key="idx"
              @click="delChange(idx, item)"
            >
              {{ item.name }}
              <el-icon size="12" style="margin-left: 2px; cursor: pointer">
                <Close />
              </el-icon>
            </div>
          </div>
          <div class="curr" style="width: 70px">
            <el-icon
              size="14"
              style="width: 60px"
              @click="onClickDeleteAllSearch"
            >
              <Delete /> 清空
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 筛选信息 -->
      <el-row :gutter="20" class="margintop">
        <el-col :span="12" class="flex">
          <el-popover
            placement="bottom-start"
            :width="100"
            :trigger="selTypeIndex == 0 ? 'hover' : ''"
          >
            <template #reference>
              <el-button type="primary" @click="onClickTypeItem(0)"
                >{{
                  zy_type == 1
                    ? selTypeIndex == 0
                      ? chanceTitle
                      : '专业/院校'
                    : chanceTitle
                }}<samp>&nbsp;</samp>
                <el-icon size="20">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
            </template>
            <div class="margintop curr" @click="onClickChanceLvItem(0)">
              {{ (zy_type == 1 ? '专业/院校 ' : '全部 ') + chance_lv_all }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(1)">
              冲 {{ chance_lv_1 }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(2)">
              稳 {{ chance_lv_2 }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(3)">
              保 {{ chance_lv_3 }}
            </div>
          </el-popover>
          <el-popover
            v-if="zy_type == 1"
            placement="bottom-start"
            :width="100"
            :trigger="selTypeIndex == 1 ? 'hover' : ''"
          >
            <template #reference>
              <el-button type="primary" @click="onClickTypeItem(1)">
                {{ selTypeIndex == 1 ? chanceTitle : '院校/专业'
                }}<samp>&nbsp;</samp>
                <el-icon size="20">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
            </template>
            <div class="margintop curr" @click="onClickChanceLvItem(0)">
              {{ (zy_type == 1 ? '院校/专业 ' : '全部 ') + chance_lv_all }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(1)">
              冲 {{ chance_lv_1 }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(2)">
              稳 {{ chance_lv_2 }}
            </div>
            <div class="margintop curr" @click="onClickChanceLvItem(3)">
              保 {{ chance_lv_3 }}
            </div>
          </el-popover>
          <el-button @click="reportchange">
            <el-icon>
              <Tickets />
            </el-icon>
            推荐报告
          </el-button>
        </el-col>
        <el-col :span="2.5">
          <el-popover
            placement="bottom"
            :width="300"
            :visible="showScreenPopover"
          >
            <template #reference>
              <el-button @click.stop="showScreenPopover = !showScreenPopover"
                >高级筛选
                <el-icon size="15">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
            </template>
            <el-form
              ref="ruleFormRef"
              label-position="top"
              :model="requestData"
            >
              <el-form-item label="中外合作">
                <el-radio-group v-model="fType">
                  <el-radio :value="0">全部</el-radio>
                  <el-radio :value="1">仅看中外</el-radio>
                  <el-radio :value="2">不看中外</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="历年征集">
                <el-radio-group v-model="hasZJ">
                  <el-radio :value="0">全部</el-radio>
                  <el-radio :value="1">仅看征集</el-radio>
                  <el-radio :value="2">不看征集</el-radio>
                </el-radio-group>
              </el-form-item>
              <div class="right">
                <el-button @click="resetForm()">重置</el-button>
                <el-button type="primary" @click="submitForm()">
                  确定
                </el-button>
              </div>
            </el-form>
          </el-popover>
        </el-col>
        <el-button>推荐范围</el-button>
        <el-col :span="7">
          <el-slider
            class="slider-score"
            v-model="scoreRange"
            range
            :min="sliderRange[0]"
            :max="sliderRange[1]"
            @change="scoreValueChange"
          />
        </el-col>
      </el-row>
      <div class="classifyheader margintop">
        <div class="flex sizebg">
          <div
            style="margin-left: 10px"
            class="alitem"
            @click="onClickSort('chance')"
          >
            录取概率
            <el-icon size="16">
              <SortDown
                :class="
                  requestData.order == 'chance' && requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
              />
              <SortUp
                :class="
                  requestData.order == 'chance' && !requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
                style="margin-left: -7px"
              />
            </el-icon>
          </div>
          <div
            style="margin-left: 20px"
            class="alitem"
            @click="onClickSort('rank')"
          >
            院校排名
            <el-icon size="16">
              <SortDown
                :class="
                  requestData.order == 'rank' && requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
              />
              <SortUp
                :class="
                  requestData.order == 'rank' && !requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
                style="margin-left: -7px"
              />
            </el-icon>
          </div>
        </div>
        <div class="flex sizeinfo">
          <div
            class="alitem"
            style="margin-right: 20px"
            @click="onClickSort('planNum')"
          >
            {{ summary.today_year }}招生计划
            <el-icon size="16">
              <SortDown
                :class="
                  requestData.order == 'planNum' && requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
              />
              <SortUp
                :class="
                  requestData.order == 'planNum' && !requestData.is_sort
                    ? 'sort-sel'
                    : ''
                "
                style="margin-left: -7px"
              />
            </el-icon>
          </div>
          <div style="width: 110px" class="center">历年</div>
          <div style="width: 110px" class="center">
            {{ summary.history_year - 0 }}
          </div>
          <div style="width: 110px" class="center">
            {{ summary.history_year - 1 }}
          </div>
          <div style="width: 110px" class="center">
            {{ summary.history_year - 2 }}
          </div>
          <div style="margin-left: 60px">填报</div>
        </div>
      </div>
      <template v-if="schoolListArr.length == 0">
        <el-empty description="暂无数据" />
      </template>
      <div ref="tableViewRef" v-loading="isRequest">
        <!--江苏 四川-->
        <jsSchoolList
          ref="schoolListRef"
          v-if="zy_type == 2"
          :schoolListArr="schoolListArr"
          :zy-num-group="zyNumGroup"
          :userSearchDate="userSearchDate"
        ></jsSchoolList>
        <!-- 山东 专业/院校-->
        <sdSchoolListMajor
          ref="schoolListRef"
          v-else-if="zy_type == 1 && selTypeIndex == 0"
          :schoolListArr="schoolListArr"
          :volunteerNumber="volunteerNumber"
          :userSearchDate="userSearchDate"
        >
        </sdSchoolListMajor>
        <!-- 山东 院校/专业-->
        <sdSchoolListCollege
          ref="schoolListRef"
          v-else-if="zy_type == 1 && selTypeIndex == 1"
          :schoolListArr="schoolListArr"
          :volunteerNumber="volunteerNumber"
          :userSearchDate="userSearchDate"
        >
        </sdSchoolListCollege>
        <!--新疆-->
        <scSchoolList
          ref="schoolListRef"
          v-else
          :schoolListArr="schoolListArr"
          :volunteerNumber="volunteerNumber"
          :userSearchDate="userSearchDate"
        ></scSchoolList>
      </div>
      <div v-show="isVIP == 0" class="noIsVIP">
        <div class="permission-tip-wrapper-tob">
          <div class="aidata">
            <p class="title">
              <span class="bigdata">大数据AI</span> 智能填志愿
            </p>
            <p>不浪费分 上好大学</p>
          </div>
          <div class="vipPro">
            <button @click="onClickOpenVIP">立即开通</button>
          </div>
        </div>
      </div>
      <div v-if="allDataFetched" class="center" style="margin-top: 20px">
        已加载全部数据
      </div>
    </div>
  </el-scrollbar>
  <!-- 江苏 -->
  <jsTypePopup
    ref="typePopupRef"
    v-if="zy_type == 2"
    :batchInfo="batchData"
    @onClickTop="onClickTop"
  ></jsTypePopup>
  <!--四川-->
  <scTypePopup
    ref="typePopupRef"
    v-else-if="zy_type == 3"
    :batchInfo="batchData"
    @onClickTop="onClickTop"
  >
  </scTypePopup>
  <!-- 山东-->
  <sdTypePopup
    ref="typePopupRef"
    v-else
    :batchInfo="batchData"
    @onClickTop="onClickTop"
  ></sdTypePopup>
  <!--用户修改信息-->
  <userUpdate ref="userUpdatesRef"></userUpdate>
  <novip ref="novipRef" />
  <reportDialog ref="report"></reportDialog>
</template>
<script setup>
import { reactive, ref, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import {
  zyList,
  batchInfo,
  schoolEnrollChance,
} from '@/api/volunteer/volunteer';
import novip from '@/components/NoVip';
import jsTypePopup from './components/jsTypePopup.vue';
import scTypePopup from './components/scTypePopup.vue';
import sdTypePopup from './components/sdTypePopup.vue';
import schoolDate from './components/schoolDate.vue'; // 学校
import career from './components/career.vue'; // 职业
import specialty from './components/specialty.vue'; // 专业
import jsSchoolList from './components/jsSchoolList.vue'; // 江苏
import scSchoolList from './components/scSchoolList.vue'; // 四川
import sdSchoolListMajor from './components/sdSchoolListMajor.vue'; // 山东
import sdSchoolListCollege from './components/sdSchoolListCollege.vue'; // 山东
import userUpdate from './components/userUpdate.vue';
import reportDialog from './components/reportDialog.vue';
import { likeList } from '@/api/user';
import _ from 'lodash';
import bus from '@/utils/bus.js';
import { ElMessageBox, ElMessage } from 'element-plus';
// 获取等效位差的公共方法
import { calculateEquivalents } from '@/utils/batchEquivalents.js';
const sgName = { 物: 1, 化: 2, 政: 6, 史: 4, 生: 3, 地: 5, 技: 7 };

// 转换选科为sgid
const convertString = (str) => {
  if (str) {
    // 1. 将字符串按“/”分割
    const keys = str.split('/');
    // 2. 将分割后的每个元素通过a对象映射转换为对应的值
    const result = keys.map((key) => sgName[key]);
    // 3. 将结果数组转为逗号分隔的字符串
    return result.join(',');
  } else {
    return '';
  }
};
const store = useStore();
const userSearchDate = computed(() => store.getters.tianbao.searchArraylist); // 筛选数据
const isVIP = computed(() => store.getters.user.userInfo.isVIP); // 是否vip
const userInfo = store.getters.user.userInfo; // 用户信息

const courseNew = ref(localStorage.getItem('courseNew')); // 修改志愿表

const infiniteScrollDisabled = ref(false);

const schoolDateinfo = ref(null);
const majorDataInfo = ref(null);
const jobDataInfo = ref(null);
const router = useRouter();
const route = useRoute();
const report = ref(null);
const tabslist = ref([
  { id: 0, name: '院校优先' },
  { id: 1, name: '专业优先' },
  { id: 2, name: '职业优先' },
]);
const like = ref({ type: '', detail: '1' });
const index = ref(0);
const novipRef = ref(null);
const scrollbarRef = ref(null);
const tableViewRef = ref(null);
const typePopupRef = ref(null);
const userUpdatesRef = ref(null);
const allDataFetched = ref(false); // 是否全部加载
const schoolListArr = ref([]); // 填报院校/专业数据列表
const summary = ref({}); // 冲保稳数据
const batchs = ref([]);
const selTypeIndex = ref(0); // 选中的填报类型 0-专业/院校 or 1-院校/专业 山东填报类型或北京专科填报类型才会显示
const zy_type = ref(0); // 填报地区类型 1-山东 2-江苏 3-四川
const volunteerNumber = ref('0'); // 可填报志愿表数量
const zyNumGroup = ref('0'); // 可填报志愿表下专业数量
const chanceTitle = ref(''); // 1标题
const chance_lv_1 = ref(0); // 冲数量
const chance_lv_2 = ref(0); // 稳数量
const chance_lv_3 = ref(0); // 保数量
const chance_lv_all = ref(0); // 全部数量
const batchData = ref({}); // 选择的批次线信息
const specialtyData = ref([]);
const batchDatas = ref([]); // 批次线信息数组
const careerData = ref([]);
// 请求数据
const requestData = reactive({
  // batch: '',
  page: 1,
  fronttype: 3,
  fType: 0, // 中外合作 0-全部
  hasZJ: 0, // 历年征集 0-全部
  order: '', // 排序 chance-录取率 rank-院校排名 planNum-招生计划
  is_sort: false, // 是否升序，false升序，true降序
});
const fType = ref(0);
const hasZJ = ref(0);

const screenData = ref([]); // 筛选数据
const isRequest = ref(false);
const resultCode = ref(null);
const scoreRange = ref([]); // 选择的分数区间
const sliderRange = ref([0, 750]); // 可选择的分数区间
const showbatchPopover = ref(false); // 是否显示批次弹窗
const showScreenPopover = ref(false); // 是否显示高级筛选弹窗
const volunteerTotal = ref(0); // 志愿表总数
const schoolData = ref([]);
const schoolListRef = ref();
const equivalents = ref([]); // 线差所需要的年份集合
const batchEqus = ref({}); // 线差所需要的批次集合
// 限报要求
const enrollTags = ref({
  isRestrictColorBW: false,
  isRestrictScore: false,
  isRestrictLanguage: false,
});
watch(
  // 监听院校筛选数据改变
  () => userSearchDate.value,
  () => {
    // console.log('筛选条件改变', userSearchDate.value);
    schoolSearchDataChange();
  },
);
// 防抖函数
function debounce(func, wait) {
  let timeout; // 定时器

  return function (...args) {
    clearTimeout(timeout); // 清除之前的定时器
    timeout = setTimeout(() => {
      func.apply(this, args); // 在 wait 时间后执行目标函数
    }, wait);
  };
}
// 定义防抖后的函数
const debouncedGetSchoolEnrollChance = debounce(getSchoolEnrollChance, 500);
const emitMajorEnrollType = (val) => {
  requestData.majorEnrollTypes = val.majorEnrollTypes;
  requestData.enrollmentType = val.enrollmentType;
  debouncedGetSchoolEnrollChance();
};
const addMojoyType = (val) => {
  requestData.mojoyType = val;
  debouncedGetSchoolEnrollChance();
};
// 处理数据，显示报考要求
bus.on('changeMajorEnrollTypes', (data) => {
  enrollTags.value[data.key] = data.val;
  addStatus();
});
// 添加报考要求
const addStatus = () => {
  schoolListArr.value.forEach((item) => {
    // item.
    if (
      item.enrollTags?.isRestrictColorBW &&
      enrollTags.value.isRestrictColorBW
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else if (
      item.enrollTags?.isRestrictScore &&
      enrollTags.value.isRestrictScore
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else if (
      item.enrollTags?.isRestrictLanguage &&
      enrollTags.value.isRestrictLanguage
    ) {
      item.majorEnrollTypesLable = '有限报要求';
    } else {
      item.majorEnrollTypesLable = '';
    }

    item.majorsInfo?.forEach((major) => {
      if (
        major.enrollTags?.isRestrictColorBW &&
        enrollTags.value.isRestrictColorBW
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else if (
        major.enrollTags?.isRestrictScore &&
        enrollTags.value.isRestrictScore
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else if (
        major.enrollTags?.isRestrictLanguage &&
        enrollTags.value.isRestrictLanguage
      ) {
        major.majorEnrollTypesLable = '有限报要求';
      } else {
        major.majorEnrollTypesLable = '';
      }
    });
  });
};
// 回到顶部
function onClickTop() {
  scrollbarRef.value.scrollTo({ top: 0, behavior: 'smooth' });
}
const changeTab = (i) => {
  index.value = i;
  schoolDateinfo.value.closeV();
  majorDataInfo.value.closeV();
  jobDataInfo.value.closeV();
};
// 院校筛选数据改变
function schoolSearchDataChange() {
  let searchData = {
    province: [],
    categories: [],
    features: [],
    natureType: [],
    eduLevelSchool: [],
    schoolNewly: [],
    scode: [],
    mcode: [],
    zcode: [],
    ssearch: '',
    msearch: '',
    zsearch: '',
  };

  for (let item of userSearchDate.value) {
    switch (item.type) {
      case 'province':
        searchData.province.push(item.code);
        break;
      case 'type':
        searchData.categories.push(item.code);
        break;
      case 'school_feature':
        searchData.features.push(item.code);
        break;
      case 'nature':
        searchData.natureType.push(item.code);
        break;
      case 'school_type':
        searchData.eduLevelSchool.push(item.code);
        break;
      case 'schoolNewly':
        searchData.schoolNewly.push(item.code);
        break;
      case 'schoolSearch':
        searchData.scode.push(item.code);
        break;
      case 'major':
        searchData.mcode.push(item.code);
        break;
      case 'job':
        searchData.zcode.push(item.code);
        break;
      case 'ssearch':
        searchData.ssearch = item.name;
        break;
      case 'msearch':
        searchData.msearch = item.name;
        break;
      case 'zsearch':
        searchData.zsearch = item.name;
    }
  }

  let data = {
    province: searchData.province.toString(),
    categories: searchData.categories.toString(),
    features: searchData.features.toString(),
    natureType: searchData.natureType.toString(),
    eduLevelSchool: searchData.eduLevelSchool.toString(),
    schoolNewly: searchData.schoolNewly.toString(),
    scode: searchData.scode.toString(),
    mcode: searchData.mcode.toString(),
    zcode: searchData.zcode.toString(),
    ssearch: searchData.ssearch,
    msearch: searchData.msearch,
    zsearch: searchData.zsearch,
  };
  // console.log('---data---', data)
  screenData.value = data;
  getSchoolEnrollChance(1);
}
let queryData = ref(null);
init();
// 初始化
function init() {
  let data = JSON.parse(route.query.data);
  queryData.value = JSON.parse(route.query.data);
  batchData.value = data.batchInfo;
  requestData.batch = batchData.value.batch;

  if (!data.update) {
    // 重置仓库中志愿表数据
    store.dispatch('tianbao/setVolunteerInfos', []);
  }

  // 设置非一键填报
  localStorage.setItem('isYJTB', 0);
  store.dispatch('tianbao/delAllSearchInfo', []);
  getSchoolEnrollChance(1);
  getZyList();
  getBatchInfo();
}
//获取关注的院校
const getLikeList = () => {
  likeList(like.value).then((res) => {
    if (res.data.code == 20000) {
      schoolData.value = res.data.data?.schoolDetail.map((item) => {
        return {
          ...item, // 保留原有的属性
          isChange: false, // 添加新属性 gbCode
        };
      });
      specialtyData.value = res.data.data?.majorDetail.map((item) => {
        return {
          ...item, // 保留原有的属性
          isChange: false, // 添加新属性 gbCode
        };
      });
      careerData.value = res.data.data?.jobDetail.map((item) => {
        return {
          ...item, // 保留原有的属性
          isChange: false, // 添加新属性 gbCode
        };
      });
    } else {
      console.log(res);
    }
  });
};
getLikeList();
// 获取志愿表列表
function getZyList() {
  zyList({ page: 0, pageSize: 0 }).then((res) => {
    // console.log(res)
    volunteerTotal.value = res.data.data.count;
  });
}
const handleTabCkick = () => {
  if (store.getters.user.userInfo.isVIP == 0) {
    novipRef.value.handleIsShowDialog();
  }
};
// 获取批次线信息
function getBatchInfo() {
  let body = { pid: userInfo.pid, course: userInfo.course, less: 1 };
  batchInfo(body).then((res) => {
    batchDatas.value = res.data.data.batches;
  });
}
/**
 * 获取填报列表
 * @param {Object} page 页码 可选参数，用于page=1
 */
function getSchoolEnrollChance(page) {
  if (page) requestData.page = page;
  // 判断非vip只能请求第一页数据
  if (isVIP.value == 0 && requestData.page != 1) {
    return;
  }
  let data = { ...requestData, ...screenData.value };

  if (selTypeIndex.value == 1) {
    data['zy_type'] = 3;
  }
  if (scoreRange.value.length >= 2) {
    data['score_min'] = scoreRange.value[0];
    data['score_max'] = scoreRange.value[1];
  }
  if (isRequest.value) return;
  isRequest.value = true;
  if (queryData.value.batchInfo.score) {
    data['score'] = queryData.value.batchInfo.score; //成绩
    data['sgid'] = convertString(queryData.value.batchInfo.sgname); //选科
    data['batch'] = queryData.value.batchInfo.batch;
    data['course'] = localStorage.getItem('course');
  } else {
    data['score'] = userInfo.score; //成绩
    data['sgid'] = convertString(userInfo.sgname);
    data['course'] = localStorage.getItem('courseNew');
  }

  schoolEnrollChance(data)
    .then((res) => {
      localStorage.setItem(
        'courseNew',
        res.data.data?.scoreConfigData?.course
          ? res.data.data.scoreConfigData.course
          : '',
      );
      resultCode.value = res.data.code;
      if (res.code == 44444) {
        ElMessage.error(res.msg);
        router.go(-1);
      } else {
        isRequest.value = false;
        const data = res.data.data || {};

        equivalents.value = data.equivalents;
        batchEqus.value = data.batchEqus;

        allDataFetched.value = data.list.length == 0;

        summary.value = data.summary;
        batchs.value = data.batchs;

        scoreRange.value[0] = data.summary.score_min;
        scoreRange.value[1] = data.summary.score_max;
        sliderRange.value[0] = data.summary.score_min_m;
        sliderRange.value[1] = data.summary.score_max_m;

        if (requestData.page == 1) {
          schoolListArr.value = [];
        }

        if (data.list.length > 0) {
          schoolListArr.value = [
            ...schoolListArr.value,
            // 获取等效位差的公共方法
            ...calculateEquivalents(data.list, batchEqus.value),
          ];
          console.log('schoolListArr.value:', schoolListArr.value);

          addStatus();
          volunteerNumber.value = data.zy_info.zy_num;
          zy_type.value = data.zy_info.zy_type;
          console.log('zy_type.value', zy_type.value);
          zyNumGroup.value = data.zy_info.zy_num_group;
          chance_lv_1.value = data.summary.chance_lv_1 || 0;
          chance_lv_2.value = data.summary.chance_lv_2 || 0;
          chance_lv_3.value = data.summary.chance_lv_3 || 0;
          chance_lv_all.value =
            chance_lv_1.value + chance_lv_2.value + chance_lv_3.value;
        }

        infiniteScrollDisabled.value = !!res.data.data.length;
        refreshChanceTitle(requestData.chance_lv || 0);
        // console.log('-------', zy_type.value)
      }
    })
    .catch((err) => {
      isRequest.value = false;
      resultCode.value = err.code || 0;
    });
}

// 点击修改分数
function onClickUpdateScore() {
  userUpdatesRef.value.openChange();
}

// 点击我的志愿表
function onClickMyVolunteerList() {
  router.push({ path: '/volunteerList' });
}

/**
 * 点击填报切换批次
 * @param {Number} index 下标
 */
function onClickFillVolunteer(index) {
  let batch = batchDatas.value[index];
  if (batchData.value.id != batch.id) {
    showbatchPopover.value = false;
    ElMessageBox.confirm(
      '切换批次后，上次填报院校以及专业全部清空',
      '是否切换当前批次,当前批次' + batchData.value.batch,
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
    ).then(() => {
      let body = { batchInfo: batch };
      let jsonStr = JSON.stringify(body);
      router.replace({ path: route.path, query: { data: jsonStr } });

      schoolListRef.value.removeVolunteerInfos();

      // 更新批次信息
      batchData.value = batchDatas.value[index];
      requestData.batch = batchData.value.batch;
      store.dispatch('tianbao/setVolunteerInfos', []);
      // 清空筛选条件
      onClickDeleteAllSearch();
      // 获取列表
      getSchoolEnrollChance(1);
    });
  }
}

/**
 * 点击切换录取率筛选项
 * @param {Number} tag 0-全部 1-冲 2-稳 3-保
 */
function onClickChanceLvItem(tag) {
  if (requestData.chance_lv != tag) {
    requestData.chance_lv = tag;

    refreshChanceTitle(tag);
    getSchoolEnrollChance(1);
  }
}

/**
 * 刷新录取率筛选标题
 * @param {Number} tag 0-全部 1-冲 2-稳 3-保
 */
function refreshChanceTitle(tag) {
  switch (tag) {
    case 0:
      if (selTypeIndex.value == 0) {
        chanceTitle.value =
          (zy_type.value == 1 ? '专业/院校 ' : '全部 ') + chance_lv_all.value;
      } else {
        chanceTitle.value =
          (zy_type.value == 1 ? '院校/专业 ' : '全部 ') + chance_lv_all.value;
      }
      break;
    case 1:
      chanceTitle.value = '冲' + chance_lv_1.value;
      break;
    case 2:
      chanceTitle.value = '稳' + chance_lv_2.value;
      break;
    case 3:
      chanceTitle.value = '保' + chance_lv_3.value;
  }
}

/**
 * 点击切换排序
 * @param {Object} type chance-录取率 rank-院校排名 planNum-招生计划
 */
function onClickSort(type) {
  if (requestData.order == type) {
    requestData.is_sort = !requestData.is_sort;
  } else {
    requestData.is_sort = false;
  }
  requestData.order = type;
  getSchoolEnrollChance(1);
}

// 分数区间改变
const scoreValueChange = _.throttle(() => {
  // console.log(val)
  getSchoolEnrollChance(1);
}, 800);

/**
 * 点击切换填报类型
 * @param {Number} index 0-专业/院校  1-院校/专业
 */
function onClickTypeItem(index) {
  if (selTypeIndex.value != index) {
    selTypeIndex.value = index;
    schoolListArr.value = [];
    chanceTitle.value = index == 0 ? '专业/院校' : '院校/专业';

    getSchoolEnrollChance(1);
  }
}

// 推荐报告
function reportchange() {
  report.value.openChange(summary.value);
}
//转换成绩后面的文字
const convertfun = () => {
  if (queryData.value.batchInfo.score) {
    return (
      queryData.value.batchInfo.sgname +
      ' ' +
      queryData.value.batchInfo.score +
      '分'
    );
  } else {
    return userInfo.sgname + ' ' + userInfo.score + '分';
  }
};

// 删除单个筛选数据
function delChange(idx, item) {
  // console.log(idx, item)
  if (item.type == 'major' || item.type == 'msearch') {
    // 专业
    majorDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'job' || item.type == 'zsearch') {
    // 职业
    jobDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'fType' || item.type == 'hasZJ') {
    // 高级
    item.type == 'fType' ? (fType.value = 0) : (hasZJ.value = 0);
    submitForm();
  } else {
    // 院校
    schoolDateinfo.value.deleteScreenItem(item);
  }
}

// 删除全部筛选数据
function onClickDeleteAllSearch() {
  if (userSearchDate.value.length > 0) {
    requestData.fType = 0;
    requestData.hasZJ = 0;
    fType.value = 0;
    hasZJ.value = 0;
    majorDataInfo.value.deleteAll();
    jobDataInfo.value.deleteAll();
    schoolDateinfo.value.deleteAll();
    store.dispatch('tianbao/saveAdvancedInfoChange', []);
  }
}

function submitForm() {
  if (requestData.fType != fType.value || requestData.hasZJ != hasZJ.value) {
    requestData.fType = fType.value;
    requestData.hasZJ = hasZJ.value;

    let arr = [];
    if (requestData.fType != 0) {
      arr.push({
        name: requestData.fType == 1 ? '仅看中外' : '不看中外',
        code: requestData.fType,
        type: 'fType',
      });
    }

    if (requestData.hasZJ != 0) {
      arr.push({
        name: requestData.hasZJ == 1 ? '仅看征集' : '不看征集',
        code: requestData.hasZJ,
        type: 'hasZJ',
      });
    }

    store.dispatch('tianbao/saveAdvancedInfoChange', arr);
    showScreenPopover.value = false;
  }
}

// 重置高级筛选
function resetForm() {
  fType.value = 0;
  hasZJ.value = 0;
}
const load = () => {
  if (!allDataFetched.value) {
    if (resultCode.value == 20000) {
      infiniteScrollDisabled.value = true;
      requestData.page += 1;
      getSchoolEnrollChance();
    }
  }
};

function onClickOpenVIP() {
  router.push({ path: '/shopserve' });
}
</script>

<style lang="scss" scoped>
.classifyheader {
  position: sticky;
  top: 0;
  z-index: 99;
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 80px;

  .sort-sel {
    color: #004cf7;
  }
}

.screen {
  min-height: 50px;
  padding: 6px 0 6px 20px;
  background-color: #f9f9f9;
  display: flex;
  overflow: hidden;
  align-items: center;

  .screenSize {
    font-size: 12px;
    font-weight: 400;
    color: #3d3d3d;
    width: 55px;
  }

  .screenTab {
    padding: 7px 10px;
    margin: 2px 0;
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-left: 10px;
  }
}

.box-card {
  margin-bottom: 50px;
  border: #e6e6e6 1px solid;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

// 改变滑块原点大小和颜色  el-slider__button
:deep() .el-slider__button {
  color: red;
  width: 40px;
  height: 30px;
  border-radius: 10px;
  z-index: 1;
  top: var(--el-slider-button-wrapper-offset);
  // transform: translateX(-50%);
  background-color: #fff;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  line-height: normal;
  outline: 0;
}

// 更改 el-slider__button-wrapper
:deep() .el-slider__button-wrapper {
  height: var(--el-slider-button-wrapper-size);
  width: var(--el-slider-button-wrapper-size);
  position: absolute;
  z-index: 1;
  top: var(--el-slider-button-wrapper-offset);
  transform: translateX(0); // 去掉滑块默认X轴翻转
  background-color: transparent;
  text-align: center;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  line-height: normal;
  outline: 0;
}

// 滑块中间显示内容
:deep() .el-slider__button-wrapper::before {
  content: attr(aria-valuetext); // !!显示的内容,注意,一定是这个
  position: absolute;
  width: 20px;
  height: 25px;
  line-height: 25px;
  border-radius: 5px;
  text-align: center;
  top: 4px;
  left: 8.5px;
  font-size: 12px;
  z-index: 999;
}

// 去掉滑块默认鼠标移入事件
:deep() .el-slider__button-wrapper.hover {
  transform: none;
}

:deep() .el-slider__button-wrapper::hover {
  transform: none;
}

.noIsVIP {
  .permission-tip-wrapper-tob {
    margin-bottom: 20px;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
    height: 300px;
    background-image: linear-gradient(#fff, #f4f4f4);

    .aidata {
      width: 100%;
      height: 100px;
      padding: 0 404px;
      margin-top: 60px;
      text-align: center;
      color: #333;
      font-size: 24px;

      .title {
        font-size: 34px;
      }

      .bigdata {
        color: var(--color-text);
      }
    }

    .vipPro {
      width: 100%;
      height: 100px;
      padding: 20px 404px;

      button {
        height: 50px;
        width: 100%;
        font-size: 18px;
        border-radius: 30px;
        color: #fff;
        border: none;
        background-color: var(--background-color);
      }
    }
  }
}
</style>
